/*
 *  Copyright 2012, Tera-soft Co., Ltd.  All right reserved.
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF TERA-SOFT CO.,
 *  LTD.  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED TO THIRD
 *  PARTIES, COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 *  WITHOUT THE PRIOR WRITTEN PERMISSION OF TERA-SOFT CO., LTD
 *
 */
package com.water.wfo.component.api.filter;

import com.alibaba.fastjson.JSONObject;
import com.water.wfo.component.api.entity.response.BasicResponse;
import com.water.wfo.component.util.StringUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author wy
 *
 */
@Component
@Order(0)
@WebFilter(filterName="formTokenFilter",urlPatterns="/*")
public class FormTokenFilter implements Filter {

	/** (non-Javadoc)
	 * @see Filter#doFilter(ServletRequest,
	 * ServletResponse, FilterChain)
	 * @param servletRequest servletRequest
	 * @param servletResponse servletResponse
	 * @param filterChain filterChain
	 * @throws IOException IOException
	 * @throws ServletException ServletException
	 */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String formToken = request.getParameter("formToken");
		String newFormToken = request.getParameter("newFormToken");

		if (null != newFormToken && "".equals(newFormToken)) {
			request.getSession().setAttribute("formToken", newFormToken);
			PrintWriter writer = response.getWriter();
			writer.print("newFormTokenOk");
			writer.flush();
			writer.close();
			return;

		}

		if (null == formToken || "".equals(formToken)) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		String sessionFormToken = request.getSession().getAttribute("formToken").toString();

		if (formToken.equals(sessionFormToken)) {
			//新令牌
			String token = StringUtil.createToken();
			request.getSession().setAttribute("formToken", token);
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		} else {
			PrintWriter writer = response.getWriter();
			BasicResponse basicResponse=new BasicResponse();
			basicResponse.buildFail("重复提交");
			writer.print(JSONObject.toJSONString(basicResponse));
			writer.flush();
			writer.close();
			return;

		}

	}
}
